#include "app_led_strip.h"
#include "led_strip.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

typedef struct {
    int num_leds;       // LED灯带中的LED数量
    uint8_t* buffer;    // 存储LED颜色数据的缓冲区
    bool initialized;    // 是否初始化标志
    bool refreshed;      // 是否已刷新标志
}LedStrip;

static led_strip_handle_t led_strip;

static void app_led_strip_task(void* pvParameters);


// 设置某个像素的颜色
void led_strip_set_pixel(LedStrip* strip, int index, int r, int g, int b) {
    if (index < 0 || index >= strip->num_leds) {
        printf("设置错误\n");
        return;
    }

    // 示例：假设buffer是一个存储颜色的数组，每个LED占3个字节(RGB)
    strip->buffer[index * 3] = r;     // 红色
    strip->buffer[index * 3 + 1] = g; // 绿色
    strip->buffer[index * 3 + 2] = b; // 蓝色
    printf("设置像素 %d 的颜色 (R: %d, G: %d, B: %d)\n", index, r, g, b);
}
esp_err_t led_strip_refresh(LedStrip* strip)
{
    if (strip == NULL || !strip->initialized) {
        return ESP_ERR_INVALID_STATE; // 错误状态
    }

    // 将缓冲区中的数据写入到LED灯带上
    esp_err_t ret = led_strip_write(led_strip, strip->num_leds, strip->buffer);
    strip->refreshed = true;
    return ret;
}



// 消息处理函数
void app_led_strip_message_handler(uint8_t* data, int len)
{
    if (data[0] == 0x01) {
        uint8_t r = data[1];
        uint8_t g = data[2];
        uint8_t b = data[3];
        led_strip_set_pixel(&led_strip, 0, r, g, b);
        led_strip_refresh(&led_strip);
    }
    if (data[0] == 0x02) {
        // 返回状态
        app_led_strip_send_message(0x02, 0x00, 0x00, 0x00);
    }
}



void app_led_strip_init()
{

    led_strip_config_t strip_config = {
        .strip_gpio_num = GPIO_NUM_21,            // The GPIO that connected to the LED strip's data line
        .max_leds = 1,                            // The number of LEDs in the strip,LED灯数量
        .led_pixel_format = LED_PIXEL_FORMAT_GRB, // Pixel format of your LED strip
        .led_model = LED_MODEL_WS2812,            // LED strip model
        .flags.invert_out = false,                // whether to invert the output signal
    };

    led_strip_rmt_config_t rmt_config = {
        .clk_src = RMT_CLK_SRC_DEFAULT,    // different clock source can lead to different power consumption
        .resolution_hz = 10 * 1000 * 1000, // RMT counter clock frequency
        .flags.with_dma = false,           // DMA feature is available on ESP target like ESP32-S3
    };

    led_strip_new_rmt_device(&strip_config, &rmt_config, &led_strip);//创建LED灯带设备

    xTaskCreate(app_led_strip_task, "led_strip_task", 1024 * 2, NULL, 10, NULL);//LED灯控制任务
}





static void app_led_strip_task(void* pvParameters)
{
    uint8_t r, g, b;
    vTaskDelay(3000);
    while (1)
    {
        LedStrip led_strip;
        //灯带的LED数量
        led_strip.num_leds = 10;
        /*
        r = rand() % 16;
        g = rand() % 16;
        b = rand() % 16;*/
        //设置灯带颜色
        led_strip_set_pixel(&led_strip, 0, r, g, b);//数量、颜色
        led_strip_refresh(&led_strip);
        //刷新
        vTaskDelay(100);
    }
}